/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: GPT4Controller.java</p>
 *
 * @author zz
 * @date 2024/4/7
 * @version 1.0
 * History:
 * v1.0.0 2024/4/7 Create
 */
package com.haohan.mess.controller;

/**
 * <p>Title: GPT4Controller</p>
 * <p>Description: </p>
 *
 * @author zz
 */

import com.haohan.mess.entity.ChatReq;
import com.haohan.mess.service.GPT4Service;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;

@RestController
@RequestMapping("/chat")
@CrossOrigin(origins = "*")
public class GPT4Controller {

    private final GPT4Service gpt4Service;

    @Autowired
    public GPT4Controller(GPT4Service gpt4Service) {
        this.gpt4Service = gpt4Service;
    }

    @PostMapping("/ask-gpt4")
    public ResponseBodyEmitter askGpt4(@RequestBody ChatReq req) throws Exception {
        final ResponseBodyEmitter emitter = new ResponseBodyEmitter();

        Call call = gpt4Service.createCall("yiios-UmmQjLPtFBlaloeE842431E8A79b439cB5B9F87d7309C052", req.getN(), req.getMessages());
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response.isSuccessful() && response.body() != null) {
                        String responseBody = response.body().string();
                        emitter.send(responseBody);
                        emitter.complete();
                    } else {
                        emitter.completeWithError(new RuntimeException("Request to GPT-4 API failed"));
                    }
                } catch (IOException e) {
                    emitter.completeWithError(e);
                } finally {
                    response.close();
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}

